<template>
  <el-select ref="dragSelect" v-model="selectVal" v-bind="$attrs" class="drag-select">
    <slot />
  </el-select>
</template>

<script>
export default {
  name: 'DragSelect'
}
</script>

<script setup>
import Sortable from 'sortablejs'

import { defineProps, ref, computed, defineEmits, onMounted } from 'vue'

const props = defineProps({
  modelValue: {
    type: Array,
    required: true
  }
})

const emits = defineEmits(['update:modelValue'])

const selectVal = computed({
  get() {
    return [...props.modelValue]
  },
  set(val) {
    emits('update:modelValue', [...val])
  }
})

onMounted(() => {
  setStart()
})

const dragSelect = ref()

const setStart = () => {
  const el = dragSelect.value.$el.querySelectorAll('.el-select__tags > span')[0]
  Sortable.create(el, {
    ghostClass: 'sortable-ghost', // Class name for the drop placeholder,,
    setData: function(dataTransfer) {
      dataTransfer.setData('Text', '')
      // to avoid Firefox bug
      // Detail see : https://github.com/RubaXa/Sortable/issues/1012
    },
    onEnd: evt => {
      const modleValue = props.modelValue
      const targetRow = modleValue.splice(evt.oldIndex, 1)[0]
      modleValue.splice(evt.newIndex, 0, targetRow)
      emits('update:modelValue', modleValue)
    }
  })
}

</script>

<style lang="scss" scoped>
.drag-select {

  :deep(.sortable-ghost) {
    opacity: .8;
    color: #fff !important;
    background: #42b983 !important;
  }

  :deep(.el-tag) {
    cursor: pointer;
  }

}
</style>
